<!-- 引入自定义css -->
<link rel="stylesheet" href="__ADMIN_CSS__/onlineChooseSeat.css">
<style type="text/css">
/*硬座*/
.hardSeat{background-image: url({$seatTypeImg[0]});}
/*软座*/
.softSeat{background-image: url({$seatTypeImg[1]});}
/*学术仓*/
.academicSeat{background-image: url({$seatTypeImg[2]});}
/*交流间*/
.intercommunionSeat{background-image: url({$seatTypeImg[3]});font-size: 36px;}
</style>
<form class="layui-form layui-form-pane" action="{:url('')}" id="editForm" method="post">
    <input type="hidden" name="areaid" value="{$areaid}">
    <input type="hidden" name="seatarr" id='seatarr' value="" lay-verify="seatarr">
    <!-- 自定义DOM  画布 -->
    <div class="mainBox">
        <!-- 画布 -->
        <div class="canvas" id="canvas" {notempty name="bgimg"} style="background-image: url({$bgimg});background-size: 100% 100%;background-repeat: no-repeat;" {/notempty}>
        {volist name="seatlist" id="vo"}
            {switch name="vo.seatType"}
                {case value="1"}<div class="hardSeat" zoom="{$vo.zoom}" dataId="{$vo.id}" style="position: absolute;top:{$vo.top}px;left:{$vo.left}px;width: {$vo.zoom*30}px; height: {$vo.zoom*30}px; line-height: {$vo.zoom*30}px; transform: rotate({$vo.rotate}deg); overflow: hidden;">{$vo.seatNum}</div>{/case}
                {case value="2"}<div class="softSeat" zoom="{$vo.zoom}" dataId="{$vo.id}" style="position: absolute;top:{$vo.top}px;left:{$vo.left}px;width: {$vo.zoom*30}px; height: {$vo.zoom*30}px; line-height: {$vo.zoom*30}px; transform: rotate({$vo.rotate}deg); overflow: hidden;">{$vo.seatNum}</div>{/case}
                {case value="3"}<div class="academicSeat" zoom="{$vo.zoom}" dataId="{$vo.id}" style="position: absolute;top:{$vo.top}px;left:{$vo.left}px;width: {$vo.zoom*30}px; height: {$vo.zoom*30}px; line-height: {$vo.zoom*30}px; transform: rotate({$vo.rotate}deg); overflow: hidden;">{$vo.seatNum}</div>{/case}
                {case value="4"}<div class="intercommunionSeat" zoom="{$vo.zoom}" dataId="{$vo.id}" style="position: absolute;top:{$vo.top}px;left:{$vo.left}px;width: {$vo.zoom*200}px; height: {$vo.zoom*100}px; line-height: {$vo.zoom*100}px; transform: rotate({$vo.rotate}deg); overflow: hidden;">{$vo.seatNum}</div>{/case}
                {default/}default
            {/switch}
        {/volist}
        </div>
        <!-- 数据 -->
        <div class="contentBox">
            <div class="layui-form-item">
                <label class="layui-form-label">背景图片</label>
                <div class="layui-input-inline upload">
                    <button type="button" name="bgimg" class="layui-btn layui-btn-primary layui-upload" lay-type="image" lay-data="{accept:'image'}">请上传图片</button>
                    <input type="hidden" class="upload-input" name="bgimg" value="">
                    <img src="{$bgimg}" style="{empty name="bgimg"}display:none;{/empty}border-radius:5px;border:1px solid #ccc" width="36" height="36">
                </div>
                <div class="layui-form-mid layui-word-aux">背景图片大小750*750</div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">座位类型</label>
                <div class="layui-input-inline" id="seatType">
                    <select class="" type="select">
                        <option value="1">普通硬座</option>
                        <option value="2">软座</option>
                        <option value="3">学术仓</option>
                        <option value="4">交流间</option>
                    </select>
                </div>
                <!-- 座位数量 -->
                <label class="layui-form-label">添加座位数</label>
                <div class="layui-input-inline">
                    <input type="text" value="10" id="seatNumber" class="layui-input" autocomplete="off" placeholder="请输入座位数量(1-30)" onKeyUp="value=value.replace(/[^\d]/g,'')">
                </div>
            </div>
            


            <!-- 自增属性 -->
            <div class="layui-form-item">
                <!-- 缩放比例 -->
                <label class="layui-form-label" style="width: 140px !important;">座位缩放比例</label>

                <div class="layui-input-inline" id="seatZoom">
                    <select name="seat_type" class="field-seat_type" type="select">
                        <option value="0.4">0.4</option>
                        <option value="0.5">0.5</option>
                        <option value="0.6">0.6</option>
                        <option value="0.7">0.7</option>
                        <option value="0.8">0.8</option>
                        <option value="0.8">0.9</option>
                        <option value="1" selected>1</option>
                        <option value="1.1">1.1</option>
                        <option value="1.2">1.2</option>
                        <option value="1.3">1.3</option>
                        <option value="1.4">1.4</option>
                        <option value="1.5">1.5</option>
                        <option value="1.6">1.6</option>
                        <option value="1.7">1.7</option>
                        <option value="1.8">1.8</option>
                        <option value="1.9">1.9</option>
                        <option value="2">2</option>
                    </select>
                </div>
                <!-- 摆放角度 -->
                <label class="layui-form-label">摆放角度</label>
                <div class="layui-input-inline">
                    <input type="text" value = "0" id="seatAngle" class="layui-input" autocomplete="off" placeholder="请输入座位的角度(0-360)" onKeyUp="value=value.replace(/[^\d]/g,'')">
                </div>
            </div>

            <!-- 请输入座位的长宽 -->
<!--             <div class="layui-form-item">
                <label class="layui-form-label">座位高度</label>
                <div class="layui-input-inline">
                    <input type="text" value="30" id="seatLength" class="layui-input field-username" name="username" lay-verify="title" autocomplete="off" placeholder="请输入座位的高度" onKeyUp="value=value.replace(/[^\d]/g,'')">
                </div>
                <label class="layui-form-label">座位宽度</label>
                <div class="layui-input-inline">
                    <input type="text" value="30" id="seatWidth" class="layui-input field-username" name="username" lay-verify="title" autocomplete="off" placeholder="请输入座位的宽度" onKeyUp="value=value.replace(/[^\d]/g,'')">
                </div>
                <label class="layui-form-label">座位圆角</label>
                <div class="layui-input-inline">
                    <input type="text" value="30" id="seatFillet" class="layui-input field-username" name="username" lay-verify="title" autocomplete="off" placeholder="请输入座位的圆角" onKeyUp="value=value.replace(/[^\d]/g,'')">
                </div>
            </div> -->
            <div class="layui-form-item">
                <label class="layui-form-label" id="submitBtn">确认添加</label>
                <label class="layui-form-label" id="deleteAll" >删除所有</label>
                <label class="layui-form-label" id="saveAndExit" lay-submit lay-filter="formSubmit">保存座位信息</label>
            </div>

        </div>
    </div>

</form>
{include file="admin@block/layui" /}

<script>
/* 修改模式下需要将数据放入此变量 */
var formData = {:json_encode($data_info)};
layui.use(['upload','form'], function() {
    var $ = layui.jquery, layer = layui.layer, upload = layui.upload,form = layui.form;
    /**
     * 附件上传url参数说明
     * @param string $from 来源
     * @param string $group 附件分组,默认sys[系统]，模块格式：m_模块名，插件：p_插件名
     * @param string $water 水印，参数为空默认调用系统配置，no直接关闭水印，image 图片水印，text文字水印
     * @param string $thumb 缩略图，参数为空默认调用系统配置，no直接关闭缩略图，如需生成 500x500 的缩略图，则 500x500多个规格请用";"隔开
     * @param string $thumb_type 缩略图方式
     * @param string $input 文件表单字段名
     */
    upload.render({
        elem: '.layui-upload'
        ,url: '{:url("admin/annex/upload?water=no&thumb=no&from=&group=")}'
        ,method: 'post'
        ,before: function(input) {
            layer.msg('文件上传中...', {time:3000000});
        },done: function(res, index, upload) {
            var obj = this.item;
            if (res.code == 0) {
                layer.msg(res.msg);
                return false;
            }
            layer.closeAll();
            var input = $(obj).parents('.upload').find('.upload-input');
            if ($(obj).attr('lay-type') == 'image') {
                input.siblings('img').attr('src', res.data.file).show();
                $('#canvas').css('background-image','url('+res.data.file+')');
            }
            input.val(res.data.file);
        }
    });
    form.verify({
        seatarr:function(value, item){ 
            if(value == ''){
                return '请添加座位'
            }
        }
    });
});
</script>
<script src="__ADMIN_JS__/footer.js"></script>

<!-- 自定义JS -->
<script type="text/javascript">
    // 获取value
    // 换算value值
    // 判断value
    // 创建节点
    // 添加删除事件
    // 为节点添加移动事件
    // 点击保存，获取所有节点的位置
    // 将所有的数据添加到json中


    // let sessionStorage = window.sessionStorage
    let submitBtn = document.querySelector('#submitBtn').addEventListener('click', submitBtnHandler)
    // 保存座位信息数据
    let jsonArray = []
    let saveAndExit = document.querySelector('#saveAndExit').addEventListener('click', saveAndExitHandler)
    // 删除所有位置信息
    let deleteAll = document.querySelector('#deleteAll').addEventListener('click', deleteAllHandler)
    // 监听座位移动
    let move = document.querySelectorAll('.canvas div')
    for(let i = 0; i < move.length; i++){
        // console.log(move[i])
        moveDiv(canvas, move[i])
    }


    // 处理函数
    function submitBtnHandler(){

        let seatType = document.querySelector('#seatType .layui-this').innerHTML
        let seatZoom = document.querySelector('#seatZoom .layui-this').innerHTML
        // let shapeType = document.querySelector('#shapeType .layui-this').innerHTML
        // let seatColor = document.querySelector('#seatColor .layui-this').innerHTML
        let seatNumber = document.querySelector('#seatNumber').value

        let seatAngle = document.querySelector('#seatAngle').value
        // let seatLength = document.querySelector('#seatLength').value
        // let seatWidth = document.querySelector('#seatWidth').value
        // let seatFillet = document.querySelector('#seatFillet').value

        if(!seatNumber || seatNumber == '0' || parseInt(seatNumber)>30){
            open("请输入有效的座位数(1-30)")
        }else if(!seatAngle){
            open("请输入有效度数")
        }
        // else if(){
        //     open("请输入有效的座位缩放比例")
        // }
        // else if(!seatLength|| seatLength == '0'){
        //     open("请输入有效的座位长度")
        // }else if(!seatWidth|| seatWidth == '0'){
        //     open("请输入有效的座位宽度")
        // }
        // else if(!seatFillet){
        //     open("请输入有效的座位圆角")
        // }
        else{
            changeValue(seatType,seatNumber,seatAngle,seatZoom)
        }

    }
    function open(msg){
        layer.open({
            title: "提示",
            offset: 'auto',
            area: ['400px', '160px'],
            content: msg,
            yes: function(index, layero){
                layer.close(index); //如果设定了yes回调，需进行手工关闭
            }
        })
    }
    function changeValue(seatType,seatNumber,seatAngle,seatZoom){
        //类型
        switch(seatType){
            case '普通硬座': seatType = 'hardSeat';break;
            case '软座': seatType = 'softSeat';break;
            case '学术仓': seatType = 'academicSeat';break;
            case '交流间': seatType = 'intercommunionSeat';break;
        }
        //数量
        let number = parseInt(seatNumber)
        //摆放角度
        let angle = parseInt(seatAngle)
        //长度
        // let height = parseInt(seatLength)
        //宽度
        // let width = parseInt(seatWidth)
        //圆角
        // let fillet = parseInt(seatFillet)

        createElement(seatType,seatNumber,seatAngle,seatZoom)
    }
    function createElement(seatType,seatNumber,seatAngle,seatZoom){

        // let num = window.sessionStorage.getItem('num') ? parseInt(window.sessionStorage.getItem('num')) : 0

        // 序号
        let divNum = document.querySelectorAll('.canvas div').length
        console.log(divNum)


        if(seatType == 'hardSeat'){
            var seatLength = parseInt(30*seatZoom)
            var seatWidth = parseInt(30*seatZoom)
        }else if(seatType == 'softSeat'){
            var seatLength = parseInt(30*seatZoom)
            var seatWidth = parseInt(30*seatZoom)
        }else if(seatType == 'academicSeat'){
            var seatLength = parseInt(30*seatZoom)
            var seatWidth = parseInt(30*seatZoom)
        }else if(seatType == 'intercommunionSeat'){
            var seatLength = parseInt(100*seatZoom)
            var seatWidth = parseInt(200*seatZoom)
        }

        for(let i = 1; i <= seatNumber; i++){
            let canvasBox = document.querySelector('.canvas')
            let content = document.createElement('div')
            content.classList.add(seatType)
            let cssText = 'width:'+seatWidth+'px;height:'+seatLength+'px;line-height:'+seatLength+'px;transform:rotate('+seatAngle+'deg);-ms-transform:rotate('+seatAngle+'deg);-moz-transform:rotate('+seatAngle+'deg);-webkit-transform:rotate('+seatAngle+'deg);-o-transform:rotate('+seatAngle+'deg);overflow:hidden;'
            content.style.cssText = cssText
            // 序号
            //content.innerHTML = i + divNum
            content.setAttribute("zoom",seatZoom)
            // window.sessionStorage.setItem('num', i + num)
            canvasBox.appendChild(content)
            // 画布<获取画布最大>

            let canvas = document.querySelector('.canvas')
            let move = document.querySelectorAll('.canvas div')
            for(let i = 0; i < move.length; i++){
                // console.log(move[i])
                moveDiv(canvas, move[i])
            }
        }  
    }
    //封装好的
    function moveDiv(oBox, oDrag){
        oDrag.onmousedown = function(ev){
            // 判断是鼠标左键  鼠标右键  还是滚轮操作  （鼠标左键才可以执行移动其他按键都是执行删除）
            if(ev.button == 0){
                var oEvent = ev || event;
                var disX = oEvent.clientX - oDrag.offsetLeft;
                var disY = oEvent.clientY - oDrag.offsetTop;
                document.onmousemove = function(ev){
                    var oEvent = ev || event;
                    let left = oEvent.clientX - disX;
                    let top = oEvent.clientY - disY;
                     
                    left<=0 && (left = 0);
                    top<=0 && (top = 0);
                    left>=(oBox.offsetWidth - oDrag.offsetWidth) && (left = oBox.offsetWidth - oDrag.offsetWidth-20)
                    top>=(oBox.offsetHeight - oDrag.offsetHeight) // top下限 && (top = oBox.offsetHeight - oDrag.offsetHeight-2)
                     
                    oDrag.style.left = left +'px'
                    oDrag.style.top = top +'px'
                    oDrag.style.position = 'absolute'
                }
                document.onmouseup = function(){
                    document.onmousemove=null;
                    document.onmouseup=null;
                }
            }else{
                // 取消浏览器默认弹窗
                window.oncontextmenu = function(){return false;}
                layui.use(['jquery'], function(){
                    layer.open({
                        title: "提示",
                        offset: 'auto',
                        area: ['400px', '160px'],
                        content: '是否需要删除该座位',
                        yes: function(index, layero){
                            var id = ev.target.attributes.dataid.value,$ = layui.jquery,url,data;
                            layer.msg('数据提交中...',{time:500000});
                            url = "{:url('seat/delOne')}";
                            data = {id:id};
                            $.ajax({
                                type: "POST",
                                url: url,
                                data: data,
                                success: function(res) {
                                    layer.msg(res.msg, {},function() {
                                        if (res.code == 1) {
                                            if (typeof(res.url) != 'undefined' && res.url != null && res.url != '') {
                                                location.href = res.url;
                                            } else {
                                                location.reload();
                                            }
                                            // 是  则删除该元素节点
                                            oBox.removeChild(oDrag)
                                            layer.close(index); //如果设定了yes回调，需进行手工关闭
                                        }
                                    });
                                }
                            });

                        }
                    })
                })
            }
            return false;
        }
    }
    // 保存位置信息到json中
    function saveAndExitHandler(){
        let move = document.querySelectorAll('.canvas div'),jsonstr,jsondata;
        for(let i = 0; i < move.length; i++){
            let json = {}
            // console.log(move[i])
            let left = move[i].style.left ? move[i].style.left : '0px'
            let top = move[i].style.top ? move[i].style.top : '0px'
            let rotate = move[i].style.transform
            let seatType = move[i].className
            let zoom = move[i].getAttribute('zoom')
            let dataId = move[i].getAttribute('dataId') ? move[i].getAttribute('dataId') : ""
            let id = i
            switch(seatType){
                case 'hardSeat': seatType = 1;break;
                case 'softSeat': seatType = 2;break;
                case 'academicSeat': seatType = 3;break;
                case 'intercommunionSeat': seatType = 4;break;
            }
            // console.log("数据")
            // console.log(seatType)
            // console.log(left)
            // console.log(top)
            // console.log(rotate)
            // console.log(id)
            // 数据组装
            json.left = left.substr(0,left.length-2)
            json.top = top.substr(0,top.length-2)
            json.rotate = rotate.replace(/[^0-9]/ig,'');
            json.seatType = seatType
            json.seatNum = id + 1
            json.zoom = zoom
            json.id = dataId
            jsonstr = JSON.stringify(json);
            jsonArray.push(jsonstr)
        }
        jsondata = jsonArray.join('|');
        document.getElementById('seatarr').value = jsondata;

        console.log("json")
        console.log(jsondata)
    }
    function deleteAllHandler(){
        let canvas = document.querySelector('.canvas')
        let move = document.querySelectorAll('.canvas div')
        console.log('111')
        if(move.length == 0){
            layer.open({
                title: "提示",
                offset: 'auto',
                area: ['400px', '160px'],
                content: '没有可删除的座位',
                yes: function(index, layero){
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                }
            })
        }else{
            layer.open({
                title: "提示",
                offset: 'auto',
                area: ['400px', '160px'],
                content: '是否需要删除全部座位',
                yes: function(index, layero){
                    layui.use(['jquery'], function(){
                        var $ = layui.jquery,url,data;
                        layer.msg('删除数据中...',{time:500000});
                        url = "{:url('seat/delAll')}";
                        data = {areaid:{$areaid}};
                        $.ajax({
                            type: "POST",
                            url: url,
                            data: data,
                            success: function(res) {
                                layer.msg(res.msg, {},function() {
                                    console.log(res)
                                    if (res.code == 1) {
                                        if (typeof(res.url) != 'undefined' && res.url != null && res.url != '') {
                                            location.href = res.url;
                                        } else {
                                            location.reload();
                                        }
                                        // 是  则删除该元素节点
                                        while(canvas.hasChildNodes()) //当elem下还存在子节点时 循环继续
                                        {
                                            canvas.removeChild(canvas.firstChild);
                                        }
                                        // 
                                        jsonArray = []
                                        console.log(jsonArray)
                                        // 清空缓存num
                                        window.sessionStorage.removeItem('num');
                                        layer.close(index); //如果设定了yes回调，需进行手工关闭 
                                    }
                                });
                            }
                        });
                    })

                }
            })
        }
    }
</script>